package org.myorg.v3;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

public class S32 extends Para3 {
	static int best_p;
	static double best_v;
	static FPeople3 best_people;


	public static String ga(int geneLength,
			int peopleNum, double p_cross,
			double p_mut, long i_num,Fc3 fc) {

		String value = "";
		String time = "";
		String it = "";
		

		long start_time = System.currentTimeMillis();
		FPeople3 my_p = new FPeople3(peopleNum,geneLength);
		FEvolution3 my_e = new FEvolution3(0.1, p_cross, p_mut);
		fc.caculate(my_p.persons);

		for (int i=0; i < i_num; i++) {

			/*if current best value are letter than global best value,
			 * replace global best value with current value
			 */
/*			double c_b = my_p.getBest().fitness;
			if (c_b > g_b) {
				g_b = c_b;
				int is_r = fc.is_r(my_p.getBest());
				if (1 == is_r ||  0 == is_r ) {
					res = res + "\t" + (System.currentTimeMillis() - start_time) 
					+"\t" + i + "\t" + fc.org_value(my_p.getBest());
					if (0 == is_r ) {
						break;
					}
				}
			}*/
			if (i%ri == 0 || i == i_num - 1) {
				value = value + "\t" + -my_p.getBest().fitness;
				time = time + "\t" + (System.currentTimeMillis() - start_time);
				it = it + "\t" + i;	
				//System.out.println(i + " ")
			}
			
			
			my_e.select(my_p);
			my_e.crossOver(my_p);
			my_e.mutation(my_p);
			fc.caculate(my_p.persons);
		}

		return value + "\n" + time + "\n" + it + "\n";
	}
	
	
	public static void main(String[] args) {
		System.out.println("enter main");
		
		for (int i=0; args != null && i < args.length; i++) {
			if (args[i].equalsIgnoreCase("-si") || args[i].equalsIgnoreCase("-iterator_num")) {
				i++;
				si_num = Integer.parseInt(args[i]);
				System.out.println("iterator number is: " + args[i]);
			} else if (args[i].equalsIgnoreCase("-ln") ||args[i].equalsIgnoreCase("-loop_num")) {
				i++;
				sln = Integer.parseInt(args[i]);
				System.out.println("loop number is: " + args[i]);
			} else {
				System.out.println("Usage: -si[iterator_num] 10000 -ln[loop_num] 25");
				System.exit(-1);
			}
        }   

		//reserve results
		String cmd = "mkdir -p ./res";
		RWF3.execmd(cmd);
		
		//for running much programmers
		String mark = RWF3.mkMark("./res/smark", sfc);
		mark = mark + "_" + sln + "_" + si_num;

		//put different results of different program to different directory 
		cmd = "mkdir -p " + spath;
		RWF3.execmd(cmd);


		for (int i = 0; i < sln; i++) {

			long st = System.currentTimeMillis();
			String r = ga(geneLength, spn, p_cross, p_mut, si_num, sfc);
			long rt = System.currentTimeMillis() - st;
			System.out.println(i + "run time is " + rt);
			System.out.println(r);
			
			RWF3.wlf(r.getBytes(),spath + "/s_r" + mark);
			
		}
		
		System.out.println("Game over");
	}

}
